package cn.edu.sxw.web.server.filters;

import cn.edu.njuit.web.server.tools.ImageTool;
import cn.edu.sxw.web.server.bean.User;
import cn.edu.sxw.web.server.service.UserTokenService;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/face")
public class ApiFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getParameter("token");
        //判断是否又token
        if (token == null) {
            JSONObject error = new JSONObject();
            error.put("error", "未登录，拒绝访问");
            response.setStatus(401);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().write(error.toJSONString());
            return;
        } else {
            UserTokenService userTokenService = new UserTokenService();
            User u = userTokenService.getUser(token);
            if (u != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                JSONObject error = new JSONObject();
                error.put("error", "token无效");
                response.setStatus(401);
                response.setContentType("application/json;charset=utf8");
                response.getWriter().write(error.toJSONString());
                return;
            }
        }
    }

    @Override
    public void destroy() {
    }
}